#===============
# * 2013 Copyright Matthew Caswell
# * Pool.pl
#-------
# * Pool language translator/compiler.
# * P.O.O.L - Perl Object Oriented Language
#===============

package PoolCompiler::Stubs;

# __START Perl
use strict;
# __END Perl

# __START NonPerl
use PoolCompiler::Exception;
# __END NonPerl

# __START Compiler
sub execute(@){
  my @argumentVector = @_;
  
  my @args = @argumentVector[1..$#argumentVector];
  
  my $stub = $argumentVector[1] . " " . join(" ", @args);
  
  exec("perl $stub");
  
  # In case the stub failed (and perl)
  exit(-1);
}

sub generate(@){
  my @argVec = @_;
  
  my $startClassFunction = $argVec[1];
  my $stubName = $argVec[2] . ".pl";
  
  my $STUB =<<EOF;
#!/usr/bin/perl
#===============================================
# * This perl script has been generated by     *
# * Matthew Caswell's original Pool compiler   *
# * (which was also written in Perl)           *
# * ------------------------------------------ *
# * The Pool function called in this script:   *
# * $startClassFunction
#===============================================
use strict;
EOF

  my @packageNames = grep length, split /\./, $startClassFunction;
  my $includeName = join("::", @packageNames[0..$#packageNames-1]);
  
  my $poolFunction = $includeName . "::$packageNames[$#packageNames]";
  
  $STUB .=<<EOF;
use $includeName;

my \@args = (\$0);
push(\@args, \@ARGV);

$poolFunction (\@args);
EOF

  open StubHandle, ">$stubName"
    or die "Can't open $stubName! $!\n";
    
  print StubHandle $STUB;
  
  close StubHandle;
  
  exit();
}

sub genExec(@){
  my @argVec = @_;
  
  my $startClassFunction = $argVec[1];
  my $stubName = $argVec[2] . ".pl";
  
  my $STUB =<<EOF;
#!/usr/bin/perl
#===============================================
# * This perl script has been generated by     *
# * Matthew Caswell's original Pool compiler   *
# * (which was also written in Perl)           *
# * ------------------------------------------ *
# * The Pool function called in this script:   *
# * $startClassFunction
#===============================================
use strict;
EOF

  my @packageNames = grep length, split /\./, $startClassFunction;
  my $includeName = join(/::/, @packageNames[0..$#packageNames-1]);
  
  my $poolFunction = $includeName . "::$packageNames[$#packageNames]";
  
  $STUB .=<<EOF;
use $includeName;

my \@args = (\$0);
push(\@args, \@ARGV);

$poolFunction (\@args);
EOF

  open StubHandle, ">$stubName"
    or die "Can't open $stubName! $!\n";
    
  print StubHandle $STUB;
  
  close StubHandle;
  
  my @args = ($stubName, "__EJECUTADO_POR_POOL");
  
  my $stubule = @args;
  
  exec("perl $stubule");
  
  # In case the stub failed (and perl)
  exit(-1);
}

# __END Compiler
1;
